package top.hmtools.ckfinder.controller;

import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;

import top.hmtools.ckfinder.base.BaseController;
import top.hmtools.ckfinder.configuration.CKFinderAutoConfiguration;
import top.hmtools.ckfinder.configuration.Configuration;
import top.hmtools.ckfinder.configuration.ConfigurationFactory;
import top.hmtools.ckfinder.configuration.IConfiguration;
import top.hmtools.ckfinder.utils.AccessControlUtil;

@Controller
public class CkFinderController extends BaseController{
	
	@Autowired
    private ServletContext servletContext;
	
	/**
	 * holds exception if any occurs during CKFinder start.
	 */
	private Exception startException;
	
	/**
	 * 项目启动时，初始化
	 */
	@PostConstruct
	public void init(){
		this.servletContext.setInitParameter("", "");
		this.servletContext.setInitParameter("", "");
		this.servletContext.setInitParameter("", "");
		
		//获取servlet上下文，并放入工具类，使其在本应用中任意位置均可以获取servlet上下文
		ServletContextFactory.setServletContext(this.servletContext);
		
		IConfiguration configuration;
		try {
			//在 web.xml 中如果配置了自定义配置类的全限定名，则尝试初始化该类对象实例
			String className = this.servletContext.getInitParameter(
				"configuration");
			if (className != null) {
				Class<?> clazz = Class.forName(className);

				//getConstructor 基于反射的 可有参、也可无参 的实例化对象的方式
				if (clazz.getConstructor(ServletConfig.class) != null) {
					configuration = (IConfiguration) clazz.getConstructor(
						ServletConfig.class).newInstance(getServletConfig());

				} else {
					//基于反射的无参实例化对象
					configuration = (IConfiguration) clazz.newInstance();
				}
			} else {
				//初始化缺省的配置对象实例
				configuration = new Configuration(getServletConfig());
			}
		} catch (Exception e) {
			Logger.getLogger(ConnectorServlet.class.getName()).log(Level.SEVERE,
				"Couldn't initialize custom configuration. Rolling back to the default one.", e);
			configuration = new Configuration(getServletConfig());
		}
		try {
			//执行初始化配置信息操作，主要是读取 指定的 “/CKFinderJava/src/main/webapp/WEB-INF/config.xml”配置文件中的内容
			configuration.init();
			//TODO 什么用途？？访问控制管理？？访问权限？？
			AccessControlUtil.getInstance().loadConfiguration(configuration);
		} catch (Exception e) {
			if (Boolean.valueOf(getServletConfig().getInitParameter("debug"))) {
				Logger.getLogger(ConnectorServlet.class.getName()).log(Level.SEVERE, "Couldn't initialize configuration object.", e);
			}
			// 设置启动异常，这样在接收到HTTP请求的时候，doGet、doPost 直接抛出此异常
			this.startException = e;
			configuration = null;
		}
		//TODO 什么用途？？单例的配置工厂，将配置信息实例对象放入该单例的工厂，便于其它地方获取配置信息
		ConfigurationFactory.getInstace().setConfiguration(configuration);
	}

	@RequestMapping(value={"#{'${"+CKFinderAutoConfiguration.URI+":}'?:'/core/connector/java/connector.java'}}","/core/connector/java/connector"})
	public void executeCommand(){
		Map<String, String[]> parameterMap = this.getRequest().getParameterMap();
		
		try {
			HttpServletResponse response = this.getResponse();
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			response.getOutputStream().write(JSON.toJSONString(parameterMap).getBytes("utf-8"));
			response.flushBuffer();
			response.getOutputStream().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


